<!--
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2024-04-18 18:44:53
 * @LastEditTime: 2024-08-31 13:41:40
 * @LastEditors:  Please set LastEditors
-->
<!-- eslint-disable no-unused-expressions -->
<!-- eslint-disable radix -->
<!-- eslint-disable no-useless-escape -->
<!-- eslint-disable no-param-reassign -->

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, orderApi, powerBankApi, productApi, userApi } from '@/api'
import { useUserStore } from '@/store'
import { getCookie } from '@/utils/common'

const userStore = useUserStore()
const { userInfo, hasLogin } = storeToRefs(userStore)
const orderId = ref('')
const typeList = reactive([
  { name: '余额充值', type: 2, pageNum: 1, loadingType: 'more', loaded: false, data: {} },
  { name: '会员卡充值', type: 3, pageNum: 1, loadingType: 'more', loaded: false, data: {} },
]);
const current = ref(0);

function tabChange(idx: number) {
  current.value = idx;
  selectedConfig.value = configDetails.value[idx]
}

// 获取设备详情
const deviceInfo = ref({})
const siteInfo = ref({})
const deviceSn = ref('')
async function getDetail() {
  uni.showLoading({
    mask: true
  })
  const { data } = await powerBankApi
    .getDeviceDetail({
      deviceSn: deviceSn.value
    })
    .finally(() => {
      uni.hideLoading()
    })
  deviceInfo.value = data?.device
  siteInfo.value = data?.site
}
const configDetails = ref([])
const selectedConfig = ref({})
const userBalance = ref(0)
const useTimesAmount = ref(0)
const cards = ref([])

// 获取消费类型
async function getOrderConsumeType() {
  uni.showLoading()
  const { data } = await powerBankApi.getOrderConsumeType({
    deviceSn: deviceSn.value,
    serviceType: 1,
  }).finally(() => {
    uni.hideLoading()
  })
  configDetails.value = data?.orderConsumeTypeConfig?.configDetails || []
  selectedConfig.value = configDetails.value[0] || {}
  userBalance.value = data?.userBalance
  // 充值卡
  typeList[1].data = configDetails.value[1]
  if (typeList[1].data) {
    typeList[1].data.cardTemplates.forEach((item, index) => {
      item.config = JSON.parse(item.config)
      console.log(item.config)
    })
  }
  // 已有的卡
  if (data?.cards.length) {
    // selectedConfig.value = configDetails.value[1] || {}
    cards.value = data?.cards
    useTimesAmount.value = 0
    for (let i = 0; i < data?.cards.length; i++) {
      const { maxCount, usedCount } = data.cards[i]
      useTimesAmount.value += maxCount - usedCount
    }
  }
  // 余额充值
  console.log(configDetails.value[0])
  const yuE = configDetails.value[0]
  if (yuE.config) {
    typeList[0].data = JSON.parse(yuE.config)
  }

}
function safeDivision(dividend: number, divisor: number) {
  if (!divisor) {
    // 处理错误或返回特定值
    console.error('除数不能为0');
    return '--'; // 或者其他合适的默认值
  }
  return (dividend / divisor).toFixed(2); // 保留两位小数
}
// 获取余额充值sku
const shopId = 2881
const productList = ref([])
const currentSku = ref(0)
async function getProduct() {
  uni.showLoading()
  const { data } = await productApi.getShopProductList({
    noPaging: true,
    detail: false,
    shopId,
    shopType: 3,
    dynamicPrice: false
  }).finally(() => {
    uni.hideLoading()
  })
  productList.value = data;
  [productList.value[0]].forEach((product, index) => {
    getSkuList(product)
  })
}
async function getSkuList(product: any) {
  if (!product) return
  const { data } = await productApi.getShopProductSkuList({
    noPaging: true,
    detail: true,
    shopType: 3,
    shopId,
    productId: product.productId
  })
  data.sort((a: { money: number }, b: { money: number }) => {
    return a.money - b.money
  })
  product.sku = data || []
}
function cardClick(index: number, sku: { payAmount: any }) {
  const { payAmount } = sku
  uni.showModal({
    title: '确认充值',
    content: `充值金额${payAmount},充值成功后无法退款`,
    cancelText: '取消充值',
    confirmText: '确认充值',
    confirmColor: '#F95B58',
    success: ({ confirm, cancel }) => {
      if (confirm) {
        submit(index)
      }
    }
  })
}
const submit = async (i: number) => {
  const shopProductSkuSelected = typeList[0].data[i]
  submitOrder(shopProductSkuSelected)
}
// 下单
async function submitOrder(shopProductSkuSelected: { id?: any; name?: any; money?: any; productSku?: { image: any; name: any }; externalConfig?: any; payAmount?: any }) {
  const orderData = {
    orderProductSkus: [
      {
        count: 1,
        shopProductSkuId: shopProductSkuSelected?.externalConfig?.shopProductSkuId,
        externalData: {
          deviceId: deviceInfo.value.id,
          type: selectedConfig.value.type,
          cardTemplateId: shopProductSkuSelected?.cardTemplateId || ''
        },
        name: shopProductSkuSelected?.externalConfig?.name,
        skuName: shopProductSkuSelected?.externalConfig.skuName,
        skuImage: shopProductSkuSelected?.externalConfig.skuImage,
        money: shopProductSkuSelected.payAmount,
        // moneyUnit: shopProductSkuWalletRule.moneyUnit || null,
        status: 0
      }
    ],
    detail: true
  }
  const { data } = await orderApi.orderAdd(orderData)
  uni.setStorageSync('orderJson', JSON.stringify(data))
  // #ifdef H5
  // const { origin, hash } = location
  // uni.setStorageSync('callback_return_url', origin + hash)
  // #endif
  // uni.navigateTo({
  //   url: '/pages/payment/index?order=true'
  // })
  if (data) {
    // location.href = `https://api.mylkjgs.com/?token=${userStore.accessToken || getCookie('HYToken') || ''}&orderId=${data.id}&scene=201`
    location.href = `https://api.mylkjgs.com/?token=${userStore.accessToken || getCookie('HYToken') || ''}&orderId=${data.id}`
  }
}

// 会员卡展示
const popShow = ref(false)
const cardIndex = ref(0)
function openCard(index: number) {
  cardIndex.value = index
  popShow.value = true
}
// 会员卡购买
function cardBuyNow() {
  if (!typeList[1].data) return
  const card = typeList[1].data.cardTemplates[cardIndex.value]
  const shopProductSkuSelected = typeof card.config === 'string'? JSON.parse(card.config) : card.config
  submitOrder({ ...shopProductSkuSelected, cardTemplateId: card.id })
  popShow.value = false
}
onShow(async () => {
  if (hasLogin.value && deviceSn.value) {
    await getOrderConsumeType()
  }
})
onLoad(async (option) => {
  if (option?.orderId) {
    orderId.value = option?.orderId
  }
  if (option?.deviceSn) {
    deviceSn.value = option?.deviceSn
    await getDetail()
  }
  await getOrderConsumeType()

  if (option?.type) {
    current.value = typeList.findIndex(item => item.type == option.type)
  }
  // getProduct()
})
</script>
<template>
  <view class="container">
    <view class="topBox">
      <view class="money times" v-if="current === 1">会员卡可用次数（次）：<text class="num">{{ useTimesAmount ||
        '0' }}</text> </view>
      <view class="money" v-else>可用余额（元）：<text class="num">{{ userBalance || '0' }}</text> </view>
    </view>
    <u-tabs :list="typeList" :is-scroll="false" v-model="current" @change="tabChange" active-color="#EC6161"
      style="margin-bottom: 20rpx;"></u-tabs>
    <!-- 会员卡 -->
    <view v-if="current === 1">
      <view v-if="typeList[1].data">
        <view v-for="(item, index) in typeList[1].data.cardTemplates" :key="item.id" class="cardItem"
          @click="openCard(index)">
          <view class="itemL">
            <view class="tit">{{ item.title }}</view>
            <view class="desc">{{ item.specifyUseDesc }}</view>
            <view class="types">
              <text class="type">{{ item.config.externalConfig.carModeUseConfig }}</text>
            </view>
          </view>
          <view class="itemR">
            <view class="price"><text>{{ item.salesPrice }}</text> 元</view>
            <view class="price-origin">原价{{ item.originalPrice }}元</view>
            <view class="prize">低至{{ safeDivision(item.salesPrice, item.maxCount) }}元/次</view>
          </view>
        </view>
      </view>
      <view v-else>
        <u-empty marginTop="50rpx"></u-empty>
      </view>
    </view>
    <!--  会员卡弹窗 -->
    <u-popup mode="bottom" v-model="popShow" :border-radius="'20'" :mask="true">
      <view class="card_info">
        <view class="cardItem">
          <view class="itemL">
            <view class="tit">{{ typeList[1].data.cardTemplates[cardIndex].title }}</view>
            <view class="desc">{{ typeList[1].data.cardTemplates[cardIndex].specifyUseDesc }}</view>
            <view class="types">
              <text class="type">{{typeList[1].data.cardTemplates[cardIndex]?.config?.externalConfig?.carModeUseConfig }}</text>
            </view>
          </view>
          <view class="itemR">
            <view class="price"><text>{{ typeList[1].data.cardTemplates[cardIndex].salesPrice }}</text> 元</view>
            <view class="price-origin">原价{{ typeList[1].data.cardTemplates[cardIndex].originalPrice }}元</view>
            <view class="prize">低至{{ safeDivision(typeList[1].data.cardTemplates[cardIndex].salesPrice,
              typeList[1].data.cardTemplates[cardIndex].maxCount) }}元/次</view>
          </view>
        </view>
        <view class="card_rule">
          <view class="tit">使用规则</view>
          <text>
            {{ typeList[1].data.cardTemplates[cardIndex].description }}
          </text>
        </view>
        <view class="card_btn" flex>
          <u-button type="primary" shape="circle" ripple :custom-style="{
            background: '#DADADA',
            width: '40%'
          }" @click="popShow = false">取消</u-button>
          <u-button type="primary" shape="circle" ripple :custom-style="{
            background: '#FF6C18',
            width: '40%'
          }" @click="cardBuyNow">立即购买</u-button>
        </view>
      </view>
    </u-popup>
    <!-- 余额充值 -->
    <view v-if="current === 0" class="c_main">
      <view class="card">
        <view class="item able" v-for="(s, index) in typeList[0].data" :key="index" @click="cardClick(index, s)">
          <!-- <view class="name">{{ s.name }}</view> -->
          <view class="price">
            <text>{{ s.payAmount }}</text>元
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fff;
  padding: 30rpx;

  .topBox {
    .money {
      font-size: 28rpx;

      .num {
        color: #F95B58;
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    margin-bottom: 30rpx;
  }

  .cardItem {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    margin-bottom: 20rpx;
    border-radius: 10rpx;

    .itemL {
      min-width: 60%;

      .tit {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .desc {
        color: #686868;
        margin-bottom: 10rpx;
        padding: 10rpx 0;
        border-bottom: 1px solid #eee;
        max-width: 60%;
      }

      .types {
        margin: 20rpx 0;

        .type {
          border-radius: 6rpx;
          padding: 6rpx 12rpx;
          background: #FFD3CD;
          color: #F95B58;
          font-size: 22rpx;
        }
      }
    }

    .itemR {
      text-align: right;

      .price {
        text {
          font-size: 40rpx;
          color: #F95B58;
          font-weight: bold;
        }
      }

      .price-origin {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
        text-decoration: line-through;
      }

      .prize {
        border-radius: 6rpx;
        padding: 6rpx 12rpx;
        background: linear-gradient(to right, #FFD3CD, #ffd3cdd1, #ffd3cd78, #ffd3cd21);
        color: #F95B58;
        font-size: 22rpx;
        margin-top: 10rpx;
      }

    }
  }
}

.c_main {
  .card {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 30rpx;
    flex-wrap: wrap;

    .item {
      width: 30%;
      border: 1px solid #f5f5f5;
      border-radius: 10rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      height: 100rpx;
      color: #bbb;

      &.able {
        background-color: #f5f5f5;
        color: #333;
      }

      .name {
        font-size: 28rpx;
        margin-bottom: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
      }

      .price {
        font-size: 30rpx;

        text {
          font-size: 36rpx;
          font-weight: bold;
        }
      }
    }
  }
}

.card_info {
  padding: 30rpx;
}

.card_rule {
  margin-top: 40rpx;

  .tit {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
}

.card_btn {
  padding: 30rpx 0;
}
</style>
